package com.qidi.socket.service;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

@Service("myChannelInitializer")
public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {
	
    @Autowired  
    TcpServerHandler tcpServerHander;


    private final static int readerIdleTimeSeconds = 40;//读操作空闲30秒
    private final static int writerIdleTimeSeconds = 50;//写操作空闲60秒
    private final static int allIdleTimeSeconds = 100;//读写全部空闲100秒
	

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
	    ChannelPipeline pipeline = ch.pipeline();
	
	/*   pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));    
       pipeline.addLast("frameEncoder", new LengthFieldPrepender(4,false));  */
	   // 解码器
			// 基于换行符号
	/*    pipeline.addLast(new LineBasedFrameDecoder(1024));
	    
	    // 基于指定字符串【换行符，这样功能等同于LineBasedFrameDecoder】
	    pipeline.addLast(new DelimiterBasedFrameDecoder(1024, false, Delimiters.lineDelimiter()));*/
	    
	    pipeline.addLast("encoder", new StringEncoder(Charset.forName("UTF-8")));
		pipeline.addLast("decoder", new StringDecoder(Charset.forName("GBK")));

        //心跳监测 读超时为10s，写超时为10s 全部空闲时间100s
        //第一个参数 60  表示读操作空闲时间
        //第二个参数 20  表示写操作空闲时间
        //第三个参数 60*10 表示读写操作空闲时间
        //第四个参数 单位
        //这个就表示 如果60秒未收到服务器信息 就重新登录 如果20秒没有信息向服务器发送 就发送心跳信息
        pipeline.addLast("ping", new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS));
		pipeline.addLast("handler",tcpServerHander);
        //pipeline.addLast("ping", new IdleStateHandler(20, 18, 10));
        //
	
	

	
    }
    

    
    

}
